package com.etc.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.Session;

import com.etc.entity.Admins;
import com.etc.entity.Fix;
import com.etc.entity.Forum;
import com.etc.entity.Housing;
import com.etc.entity.Message;
import com.etc.entity.Person;
import com.etc.entity.Prices;
import com.etc.entity.Users;
import com.etc.service.AdminsService;
import com.etc.service.FixService;
import com.etc.service.ForumService;
import com.etc.service.HousingService;
import com.etc.service.PersonService;
import com.etc.service.PricesService;
import com.etc.service.UsersService;
import com.etc.service.impl.AdminsServiceImpl;
import com.etc.service.impl.FixServiceImpl;
import com.etc.service.impl.ForumServiceImpl;
import com.etc.service.impl.HousingServiceImpl;
import com.etc.service.impl.PerviceServiceImpl;
import com.etc.service.impl.PricesServiceImpl;
import com.etc.service.impl.UsersServiceImpl;
import com.etc.util.PageData;

/**
 * Servlet implementation class UsersServlet
 */
@WebServlet("/us.do")
public class UsersServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	UsersService usersservice = new UsersServiceImpl();
	PricesService pricesservice = new PricesServiceImpl();
	FixService fixservice = new FixServiceImpl();
	ForumService forumService = new ForumServiceImpl();
	PersonService pService = new PerviceServiceImpl();
	AdminsService adminsServlet = new AdminsServiceImpl();
	private HousingService hService=new HousingServiceImpl();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UsersServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String op = "";
		//对op的值进行判断如不为空给他获取新值
		if (request.getParameter("op") != null) {
			op = request.getParameter("op");
		}
		//登入判断，获取文本框内传递额值
		if (op.equals("login")) {
			System.out.println("login");
            	List<Users> users = getUserNamePwd(request);
            	if(users.size() == 0){
    				//用户不存在
    				System.out.println("当前用户不存在");
    				request.setAttribute("defeat0", "defeat0");	
    				request.getRequestDispatcher("login.jsp").forward(request, response);
    				System.out.println("登入失败");
    			}else if(users.get(0).getUserState()==1){
    				//住户登入成功
    				System.out.println("登入成功");
    				//1-11 判断是否有选中了记住我 复选框
    				request.getSession().setAttribute("username",users.get(0).getUserName());
    				request.getSession().setAttribute("userpwd",users.get(0).getUserPwd());
    				System.out.println("flag:   "+ request.getAttribute("flag"));
    				System.out.println("ck-remember :"+request.getParameter("ck-remember"));
    				if(request.getParameter("ck-remember")!=null)
    				{
    					//用选择了记住密码
    					String name = request.getParameter("ck-remember");
    					//其实我们需要将登录的用户名存储在cookie中
    					//有的浏览器不支持中文 ....
    					Cookie cookie = new Cookie(name, users.get(0).getUserName());
    					
    					response.addCookie(cookie);
    					String cook =request.getCookies().toString();
    					System.out.println("cookie : "+cook);
    				}
    				
    				String sess =request.getSession().getAttribute("username").toString();
					System.out.println("session : "+sess);
		
					//根据用户名查询房间号
					String username =request.getSession().getAttribute("username").toString();
					System.out.println("session : "+username);
					List<Person> personname = pService.SelPersonName(username);

					if(personname.size()==0) {
						Person person = new Person(username);
						pService.AddPerson2(person);
						//转发用户的用户昵称和头像使他能够被调用
						String personImg = pService.SelPersonAll(sess).get(0).getPersonImg();
						String personNickName = pService.SelPersonAll(sess).get(0).getPersonNickName();
						request.setAttribute("personImg",personImg );
						request.setAttribute("personNickName",personNickName );
	    				
						//2调用service中的方法
						List<Housing> Housinglist=hService.SelHousingAll();
						//3传递数据给jsp可以使用内置对象request,对象原型是HttpServletRequest
						request.setAttribute("Housinglist", Housinglist);
						//4跳转到jsp页面去？ 转发

						
						
	    				Users list = usersservice.SelUsersAll(users.get(0).getUserName());
	    				System.out.println(list);
	    				request.setAttribute("list", list);
	    				request.getRequestDispatcher("index.jsp").forward(request, response);
					}else {
						String personImg = pService.SelPersonAll(sess).get(0).getPersonImg();
						String personNickName = pService.SelPersonAll(sess).get(0).getPersonNickName();
						request.setAttribute("personImg",personImg );
						request.setAttribute("personNickName",personNickName );
	    				
						//2调用service中的方法
						List<Housing> Housinglist=hService.SelHousingAll();
						//3传递数据给jsp可以使用内置对象request,对象原型是HttpServletRequest
						request.setAttribute("Housinglist", Housinglist);
						//4跳转到jsp页面去？ 转发

						
						
	    				Users list = usersservice.SelUsersAll(users.get(0).getUserName());
	    				System.out.println(list);
	    				request.setAttribute("list", list);
	    				request.getRequestDispatcher("index.jsp").forward(request, response);
					}
					

    			}else if(users.get(0).getUserState()==2){
    				//管理员登入成功
    				System.out.println("登入成功");
    				//1-11 判断是否有选中了记住我 复选框
    				request.getSession().setAttribute("username",users.get(0).getUserName());
    				request.getSession().setAttribute("userpwd",users.get(0).getUserPwd());

    				System.out.println("ck-remember :"+request.getParameter("ck-remember"));
    				if(request.getParameter("ck-remember")!=null)
    				{
    					//用选择了记住密码
    					String name = request.getParameter("ck-remember");
    					//其实我们需要将登录的用户名存储在cookie中
    					//有的浏览器不支持中文 ....
    					Cookie cookie = new Cookie(name, users.get(0).getUserName());
    					
    					response.addCookie(cookie);
    					String cook =request.getCookies().toString();
    					System.out.println("cookie : "+cook);
    				}
    				
    				Users list = usersservice.SelUsersAll(users.get(0).getUserName());
    				System.out.println(list);
    				request.setAttribute("list", list);
    				request.getRequestDispatcher("admin_users.jsp").forward(request, response);
    			}
    			else if(users.get(0).getUserState()==0) {
    				//用户未激活
    				System.out.println("当前用户未启用");
    				request.setAttribute("defeat01", "defeat01");	
    				request.getRequestDispatcher("login.jsp").forward(request, response);
    				System.out.println("登入失败");
    			
			}
			}
			
		else{
			
			// 1  除了登录以外的其他管理员的操作，都需要验证session
			// 2 request.getSession
			String url = "personal.jsp";
			if ( request.getSession().getAttribute("username") != null ) {
				
				if (op.equals("")) {
					
					// 调用的是doQuery的方法
					doQuery(request, response, url);
				} else if (op.equals("query")) {
					url = "personal_rent.jsp";

					doQuery(request, response, url);
				}
				else if (op.equals("queryBypage")){
					//房租水电查询
					System.out.println("queryBypage");
					//根据用户名查询房间号
					String sess =request.getSession().getAttribute("username").toString();
					System.out.println("session : "+sess);
					//根据登入用户名进行房间号的查找
					Users users = usersservice.SelUserDoorNo(sess);
					System.out.println("users : "+users.getUserDoorNO());
					
					//转发用户的用户昵称和头像使他能够被调用
					String personImg = pService.SelPersonAll(sess).get(0).getPersonImg();
					String personNickName = pService.SelPersonAll(sess).get(0).getPersonNickName();
					request.setAttribute("personImg",personImg );
					request.setAttribute("personNickName",personNickName );
					
					//根据用户门牌号查询当前用户水电信息
					List<Prices> list =pricesservice.SelPricesUsers(users.getUserDoorNO());
					System.out.println(list);
					request.setAttribute("list", list);
					request.getRequestDispatcher("personal_rent.jsp").forward(request, response);
					
				}else if(op.equals("upduserprice")) {
					//修改房租水电信息
					System.out.println("upduserprice");
					//用户修改信息
					String sess =request.getSession().getAttribute("username").toString();
					Users users = usersservice.SelUserDoorNo(sess);;
					
					//从jsp进行传递参数的获取
					int  priceId =Integer.parseInt(request.getParameter("priceId"));
					String priceRemark = request.getParameter("priceRemark");
							
					//转发用户的用户昵称和头像使他能够被调用
					String personImg = pService.SelPersonAll(sess).get(0).getPersonImg();
					String personNickName = pService.SelPersonAll(sess).get(0).getPersonNickName();
					request.setAttribute("personImg",personImg );
					request.setAttribute("personNickName",personNickName );
			
					//根据jsp获取的字段进行修改方法的调用
					Prices prices = new Prices(priceId, priceRemark);
					boolean flag = pricesservice.UpdRemark(prices);
					List<Prices> list =pricesservice.SelPricesUsers(users.getUserDoorNO());
					//刷新页面
					System.out.println(list);
					request.setAttribute("list", list);
					request.getRequestDispatcher("personal_rent.jsp").forward(request, response);
				}
				else if (op.equals("queryFix")){
					//查询故障报修信息
					System.out.println("queryFix");
					//根据用户名查询房间号
					String sess =request.getSession().getAttribute("username").toString();
					System.out.println("session : "+sess);
					String userna =request.getSession().getAttribute("username").toString();
					String houseName = usersservice.SelUsersAll(userna).getHouseName();
					String houseDoorNo = usersservice.SelUsersAll(userna).getUserDoorNO();
					System.out.println(houseName+"  "+houseDoorNo);
					
					request.setAttribute("houseName", houseName);
					request.setAttribute("houseDoorNo", houseDoorNo);
					
					//根据登入用户名进行房间号的查找
					Users users = usersservice.SelUserDoorNo(sess);;				
					System.out.println("users : "+users.getUserDoorNO());
					
					//转发用户的用户昵称和头像使他能够被调用
					String personImg = pService.SelPersonAll(sess).get(0).getPersonImg();
					String personNickName = pService.SelPersonAll(sess).get(0).getPersonNickName();
					request.setAttribute("personImg",personImg );
					request.setAttribute("personNickName",personNickName );
					
					
					//根据用户门牌号查询当前用户设备维护信息
					List<Fix> list =fixservice.SelFixUsers(users.getUserDoorNO());

					System.out.println(list);
					request.setAttribute("list", list);
					request.getRequestDispatcher("personal_fix.jsp").forward(request, response);	
				}else if(op.equals("addfix")) {
					//故障报修添加
					System.out.println("addfix");
					//获取用户输入的值
					String userna =request.getSession().getAttribute("username").toString();
					String houseName = usersservice.SelUsersAll(userna).getHouseName();
					String houseDoorNo = usersservice.SelUsersAll(userna).getUserDoorNO();
					request.setAttribute("houseName", houseName);
					request.setAttribute("houseDoorNo", houseDoorNo);
					String fixContent = request.getParameter("fixContent");
					//调用fixService  添加方法
					Fix fix = new Fix(houseName, houseDoorNo, fixContent);
					boolean flag = fixservice.AddFix(fix);
					if(flag) {
						//添加成功
						request.setAttribute("defeat4", "defeat4");
						String sess =request.getSession().getAttribute("username").toString();
						//根据登入用户名进行房间号的查找
						Users users = usersservice.SelUserDoorNo(sess);;
						
						//根据用户门牌号查询当前用户设备维护信息
						List<Fix> list =fixservice.SelFixUsers(users.getUserDoorNO());
						//刷新页面
						request.setAttribute("list", list);
						request.getRequestDispatcher("personal_fix.jsp").forward(request, response);
					}
				}
				else if(op.equals("addmsg")) {
					//社区评论添加
					System.out.println("addmsg");
					//获取用户输入的值
					String articleTitle = request.getParameter("articleTitle");		//标题
					String articleContent = request.getParameter("articleContent");	//内容
					String userName =request.getSession().getAttribute("username").toString();					
					//调用fixService  添加方法
					Forum forum = new Forum(articleTitle, articleContent, userName);
					boolean flag = forumService.AddForum(forum);
					if(flag) {
						//根据用户名查询房间号
						String sess =request.getSession().getAttribute("username").toString();
						System.out.println("session : "+sess);
						//根据登入用户名进行房间号的查找
						Users users = usersservice.SelUserDoorNo(sess);
						System.out.println("users : "+users.getUserDoorNO());
						
						//转发用户的用户昵称和头像使他能够被调用
						String personImg = pService.SelPersonAll(sess).get(0).getPersonImg();
						String personNickName = pService.SelPersonAll(sess).get(0).getPersonNickName();
						request.setAttribute("personImg",personImg );
						request.setAttribute("personNickName",personNickName );
						//发布新的社区评论
						System.out.println("你已经成功发布新的评论，请在下方展示栏浏览！");
						request.setAttribute("defeat5", "defeat5");
						request.getRequestDispatcher("personal_msg.jsp").forward(request, response);
					}
				}else if(op.equals("queryMsg")) {
					// 操作针对分页的操作
					// 三个参数 从页面来的
					int page = 1;
					int pageSize = 5;
					String strLike = "";
					if (request.getParameter("page") != null) {
						page = Integer.valueOf(request.getParameter("page"));
					}
					if (request.getParameter("limit") != null) {
						pageSize = Integer.valueOf(request.getParameter("limit"));
					}
					if (request.getParameter("strLike") != null) {
						strLike = request.getParameter("strLike");
					}

					//根据用户名查询房间号
					String sess =request.getSession().getAttribute("username").toString();
					System.out.println("session : "+sess);
					//根据登入用户名进行房间号的查找
					Users users = usersservice.SelUserDoorNo(sess);
					System.out.println("users : "+users.getUserDoorNO());
					
					//转发用户的用户昵称和头像使他能够被调用
					String personImg = pService.SelPersonAll(sess).get(0).getPersonImg();
					String personNickName = pService.SelPersonAll(sess).get(0).getPersonNickName();
					request.setAttribute("personImg",personImg );
					request.setAttribute("personNickName",personNickName );
					
					PageData<Message> pageData = forumService.GetForumimg(page, pageSize, strLike);
					//System.out.println(""+pageData);
					//System.out.println("pagedata.size :" + pageData.getData().size());
					pageData.getData().forEach(System.out::println);
					request.setAttribute("pageData", pageData);
					request.setAttribute("pageDataSize", pageData.getData().size());
					request.setAttribute("strLike", strLike);
					request.getRequestDispatcher("personal_msg.jsp").forward(request, response);
				}
				else if(op.equals("updpwd")) {
					//修改用户密码功能
					System.out.println("updpwd");
					
					//获取用户输入的值
					String userName =request.getSession().getAttribute("username").toString();
					String userPwd = request.getSession().getAttribute("userpwd").toString();
					//获取当前文本康输入的值
					String oldPassword = request.getParameter("oldPassword");//旧密码
					String password = request.getParameter("password");		//新密码
					String repassword = request.getParameter("repassword"); //确认新密码

					System.out.println(userName+" : "+userPwd+" : "+oldPassword);

					if(userPwd.equals(oldPassword)) {
						//根据用户名查询房间号
						String sess =request.getSession().getAttribute("username").toString();
						System.out.println("session : "+sess);
						//根据登入用户名进行房间号的查找
						Users users = usersservice.SelUserDoorNo(sess);
						System.out.println("users : "+users.getUserDoorNO());
						
						//转发用户的用户昵称和头像使他能够被调用
						String personImg = pService.SelPersonAll(sess).get(0).getPersonImg();
						String personNickName = pService.SelPersonAll(sess).get(0).getPersonNickName();
						request.setAttribute("personImg",personImg );
						request.setAttribute("personNickName",personNickName );
						//旧密码输入成功
						System.out.println("当前密码判断成功");
						
						if(password.length()>=6 && password.length()<=16) {
							if(password.equals(repassword)) {
								//两次新密码相等  调用修改密码方法
								Users users1 = new Users(userName, repassword);
								boolean flag = usersservice.UpdUsersPwd(users1);
								if(flag) {
									System.out.println("修改成功");
									request.setAttribute("personImg",personImg );
									request.setAttribute("personNickName",personNickName );
									//传值给personal_repwd.jsp页面，弹窗提示并返回登入页面
									request.setAttribute("success", "success");
									request.getRequestDispatcher("personal_repwd.jsp").forward(request, response);
								}
							}else {
								request.setAttribute("personImg",personImg );
								request.setAttribute("personNickName",personNickName );
								//两次密码输入不一致
								System.out.println("修改失败，两次密码不一致");
								request.setAttribute("defeat2", "defeat2");
								request.getRequestDispatcher("personal_repwd.jsp").forward(request, response);
							}
						}else {
							request.setAttribute("personImg",personImg );
							request.setAttribute("personNickName",personNickName );
							//新密码长度不符合
							System.out.println("当前密码长度不符合，请重试");
							request.setAttribute("defeat3", "defeat3");
							request.getRequestDispatcher("personal_repwd.jsp").forward(request, response);
						}
					}else {
						//根据用户名查询房间号
						String sess =request.getSession().getAttribute("username").toString();
						System.out.println("session : "+sess);
						//根据登入用户名进行房间号的查找
						Users users = usersservice.SelUserDoorNo(sess);
						System.out.println("users : "+users.getUserDoorNO());
						
						//转发用户的用户昵称和头像使他能够被调用
						String personImg = pService.SelPersonAll(sess).get(0).getPersonImg();
						String personNickName = pService.SelPersonAll(sess).get(0).getPersonNickName();
						request.setAttribute("personImg",personImg );
						request.setAttribute("personNickName",personNickName );
						//旧密码输入错误
						System.out.println("当前密码错误，请重试");
						request.setAttribute("defeat", "defeat");
						request.getRequestDispatcher("personal_repwd.jsp").forward(request, response);
					}
			
				}
				else if (op.equals("updpwd1")){
					//根据用户名查询房间号
					String sess =request.getSession().getAttribute("username").toString();
					System.out.println("session : "+sess);
					//转发用户的用户昵称和头像使他能够被调用
					String personImg = pService.SelPersonAll(sess).get(0).getPersonImg();
					String personNickName = pService.SelPersonAll(sess).get(0).getPersonNickName();
					request.setAttribute("personImg",personImg );
					request.setAttribute("personNickName",personNickName );
					request.getRequestDispatcher("personal_repwd.jsp").forward(request, response);
					
				}
					else if (op.equals("updperson")) {
					//这里做用户个人信息的修改
					//先判断该用户在数据库中是否存在，已存在执行修改方法，不存在 执行新增方法
					//1.判断用户是否存在
					String sess =request.getSession().getAttribute("username").toString();
					List<Person> list = pService.SelPersonName(sess);
					if(list.size() == 0) {
						//添加用户信息
						String personName = request.getParameter("username");
						String personNickName = request.getParameter("personNickName");
						String personSex = request.getParameter("sex");
						String personImg = request.getParameter("avatar");
						String personJob = request.getParameter("personJob");
						String personEmail = request.getParameter("email");
						String personSign = request.getParameter("remarks");
						Person person = new Person(personName, personNickName, personSex, personImg, personJob, personEmail, personSign);
						boolean flag = pService.AddPerson(person);
						if(flag) {
							//判断用户是否增加成功
							//传值给personal_repwd.jsp页面，弹窗提示并返回登入页面
							request.setAttribute("success2", "success2");
							request.getRequestDispatcher("personal.jsp").forward(request, response);
						}
						
					}else { 
						//修改用户信息
						String personName = request.getParameter("username");
						String personNickName = request.getParameter("nickname");
						String personSex = request.getParameter("sex");
						String personImg = request.getParameter("avatar");
						String personJob = request.getParameter("personJob");
						String personEmail = request.getParameter("email");
						String personSign = request.getParameter("remarks");
						Person person = new Person(personName,personNickName, personSex, personImg, personJob, personEmail, personSign);
						System.out.println("person2"+person);
						boolean flag = pService.UpdPerson(person);
						if(flag) {
							//判断用户是否修改成功
							//传值给personal_repwd.jsp页面，弹窗提示并返回登入页面
							request.setAttribute("update2", "update2");
							request.getRequestDispatcher("personal.jsp").forward(request, response);
						}
					}						
				}else if(op.equals("queryPerson")) {
					//传递用户名查询用户全部信息
					String sess =request.getSession().getAttribute("username").toString();
					List<Person> list = pService.SelPersonAll(sess);
					System.out.println("queryPerson"+list);
					//对list获取到的数据赋值给用户定义的变量
					String personNickName = list.get(0).getPersonNickName();
					String personSex = list.get(0).getPersonSex();
					String personImg = list.get(0).getPersonImg();
					String personJob = list.get(0).getpersonJob();
					String personEmail = list.get(0).getPersonEmail();
					String personSign = list.get(0).getPersonSign();
					//把参数传递给person.jsp展示
					request.setAttribute("personNickName", personNickName);
					request.setAttribute("personSex", personSex);
					request.setAttribute("personImg", personImg);
					request.setAttribute("personJob", personJob);
					request.setAttribute("personEmail", personEmail);
					request.setAttribute("personSign", personSign);
					request.getRequestDispatcher("personal.jsp").forward(request, response);
				}
				else if(op.equals("removesession")) {
					
					//查询所有房源信息
					List<Housing> Housinglist=hService.SelHousingAll();
					//将信息传递给首页
					request.setAttribute("Housinglist", Housinglist);
					
					//退出后清除所有的session信息
					request.getSession().invalidate();
					request.getRequestDispatcher("index.jsp").forward(request, response);
					
				}
			}

		}
		
	}

	private List<Users> getUserNamePwd(HttpServletRequest request) {
		
		String userName = request.getParameter("username");
		String userPwd = request.getParameter("userpwd");

		System.out.println("userName :" + userName + ", userPwd: " + userPwd);

		List<Users> users = usersservice.SelUsersPwd(userName , userPwd);
		System.out.println(users);
		return users;
	} 
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
	private void doQuery(HttpServletRequest request, HttpServletResponse response, String url)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String userName = request.getParameter("username");
		String userPwd = request.getParameter("userpwd");
		List<Users> users = usersservice.SelUsersPwd(userName , userPwd);
		// 2 控制器一侧[servet]调用的是service中的方法
		
		Users list = usersservice.SelUsersAll(users.get(0).getUserName());
		// model2和之前不一样的地方是 此处获得了数据之后，我们不会在这里直接显示，而是将数据传递给jsp页面去进行显示
		// 3 传递数据给jsp可以使用内置对象 request,对象原型是 HttpServletRequest
		request.setAttribute("list", list);
		// 4 跳转到jsp页面去? 转发
		request.getRequestDispatcher(url).forward(request, response);
	}

}